<template>
	<div class="page-wrapper">	
		<div style="height:8%; padding-bottom:var(--mPadding);">
			<div class="flex-btn large" @click=" visible = true ">
				<img :src="Icon" />
				<span>上报整改登记</span>
			</div>
		</div>
		<div style="height:92%">
			<TableWrapper :style="{ height:'100%' }" :controls="controls" :pageInfo="pageInfo" :sourceData="tableData" :column="column" :total="total"  @search="handleSearch" />
		</div>
		<!-- 新建巡检对象模板 弹窗 -->
		<AddCorrectionDrawer v-model:visible="visible" @refresh="fetchCorrectionList" />
		<!-- 处理弹窗 -->
		<StatusModal v-model:info="info" @refresh="fetchCorrectionList" />
		<!-- 资源预览弹窗 -->
		<el-dialog v-model="sourceVisible" class="opacity" width="60vw" @close="handleClose" >
			<el-carousel height="60vh" :autoplay="false"
				:arrow="sourceList.length > 1 ? 'always' : 'never'">
				<el-carousel-item v-for="(item, index) in sourceList" :key="index">
					<video v-if="checkSourceType(item.filePath) === 'video'" controls
						style="width:100%; height:100%; ">
						<source :src="`${getFullPath(item.filePath)}`">
					</video>
					<div v-else-if="checkSourceType(item.filePath) === 'img'" :style="{
                        width: '100%',
                        height: '360px',
                        backgroundRepeat: 'no-repeat',
                        backgroundImage: `url(${getFullPath(item.filePath)})`,
                        backgroundSize: 'contain',
                        backgroundPosition: '50% 50%'
                    }">
					</div>
				</el-carousel-item>
			</el-carousel>
		</el-dialog>
	</div> 
</template>

<script setup>
	import { reactive, onMounted, watch, computed, ref, h } from 'vue';
	import { useRouter, useRoute } from 'vue-router';
	import { useGlobalStore } from '@/stores/global';
	import { getCorrectionList, setWorkOrder } from '@/api/correction.js';
	import { getGroupList, getUserList } from '@/api/group.js';
	import { getFieldAttrs } from '@/api/cycle.js';
	import { getTplList, getLabelList, getMeterTypeList, delTpl, getFullPath } from '@/api/tpl.js';
	import { ElMessage, ElPopconfirm, ElInput  } from 'element-plus'
	import TableWrapper from '@/components/TableWrapper/index.vue';
	import ConfirmDel from '@/components/ConfirmDel.vue';
	// import TaskUpdateModal from './TaskUpdateModal.vue';
    import { formatDateTime } from '@/utils/date';
	import AddCorrectionDrawer from './AddCorrectionDrawer.vue';
	import StatusModal from './StatusModal.vue';
	import Icon from '@/assets/icon-add.png';

	const global = useGlobalStore();
	const router = useRouter();
	const route = useRoute();
	const tableData = ref([]);
	const visible = ref(false);
	const info = ref({ visible:false, forEdit:false });
	const pageInfo = reactive({ page:1, pageSize:10 });
	const total = ref(0);
	const userMaps = ref({});
	const userList = ref([]);
	const groupList = ref([]);
	const groupTotal = ref(0);
	const attrList = ref([]);
	const controls = ref([
		{ type:'input', paramKey:'codeOrName', placeholder:'输入名称查询' },
		{ type:'input', paramKey:'problemDescription', placeholder:'请输入整改内容搜索' },
		{ type:'daterange', paramKey:'startTime', clearable:true },
		{ type:'select', paramKey:'rectifyStatus', placeholder:'状态', payload:Object.keys(global.correctionStatusMaps).map(key=>({ label:global.correctionStatusMaps[key].text, key }))  },
	]);
	const sourceList = ref([]);
	const sourceVisible = computed(()=>{
		return sourceList.value.length ? true : false;
	})
	const videoTypes = ['mp4', 'ogg', 'flv', 'avi', 'wmv'];
	const imgTypes = ['jpg', 'jpeg', 'png'];
	function checkSourceType(name){
	    let temp = name ? name.split('.') : '';
	    let type = temp.length > 1 ? temp[temp.length - 1] : '';
	    return videoTypes.includes(type) ? 'video' : imgTypes.includes(type) ? 'img' : ''
	}
	
	function handleClose(){
		sourceList.value = [];
	}
	
	watch([groupList, userList, attrList], ()=>{
		controls.value[1] = { type:'select', paramKey:'groupId', payload:groupList.value, total:groupTotal.value, placeholder:'请选择分组', labelKey:'groupId', labelName:'groupName' };
		controls.value[2] = { type:'select', paramKey:'userId', payload:userList.value, total:userList.value.length, placeholder:'请选择负责人', labelKey:'userId', labelName:'userName' };
		controls.value[3] = { type:'select', paramKey:'attrId', payload:attrList.value, total:attrList.value.length, placeholder:'请选择位置', labelKey:'attrId', labelName:'attrName' };
	})
	
	const actionMaps = {
        1:(row)=>[
			h('div', { onClick:()=>{  info.value = { visible:true, row }  }}, [h('i', { class:'ri-edit-line' }), h('span', null, '处理')]),
			h('div', { onClick:()=>{ handleOrder(row.rectifyId) }}, [h('i', { class:'ri-eye-line' }), h('span', null, '转工单')]),
		],
		
	}
    const column = [
        // { label:'编号', prop:'missionCode', width:'10%'  }, 
		{ label:'登记时间', width:'10%', hasTpl:true, render:row=>({ com:h('div', null, row.createTime ? row.createTime.replace('T', ' ').slice(0, row.createTime.length - 3): '--')})},
		{ label:'巡检人/上报人', width:'8%', prop:'userName' },
		{ label:'巡检对象', width:'12%', prop:'targetName' },
		{ label:'巡检项名称', width:'12%', prop:'itemName' },
		{ label:'问题照片/视频', width:'10%', hasTpl:true, render:row=>{
			let obj = row.inspectionRectifyRegisterFilesList && row.inspectionRectifyRegisterFilesList.length ? h('div', { onClick:()=> sourceList.value = row.inspectionRectifyRegisterFilesList, style:{ color:'var(--primaryColor)', cursor:'pointer'}}, '查看' ) : h('div', null, '--');
			return { com:obj }
		}},
		{ label:'问题描述', width:'10%', prop:'problemDescription' },
		{ label:'状态', width:'8%', hasTpl:true, render:row=>{ const status = global.correctionStatusMaps[row.rectifyStatus] || {}; return { com:h('span', { style:{ color:status.color } }, status.text || '未知') } }},
		{ label:'参数记录', width:'10%', prop:'valueRemark', hasTpl:true, render:row=>h('div', null, row.valueRemark || '--')},
		{ label:'处理时间', width:'10%', hasTpl:true, render:row=> ({ com:h('div', null, row.rectifyTime ? row.rectifyTime.replace('T', ' ').slice(0, row.rectifyTime.length - 3): '--') })},
		{ label:'处理结果', width:'10%', prop:'rectifyStatus', hasTpl:true, render:row=>{
            let obj = global.correctionStatusMaps[row.rectifyStatus] ;
            let str = obj ? obj.text : '--';
            return { com:h('div', null, str ), val:str };
        }},
		{ label:'操作', width:'12%', hasTpl:true, render:(row)=>{
			return { com:h('div', { class:'action-container'}, actionMaps[row.rectifyStatus] ? actionMaps[row.rectifyStatus](row) : '--' )};
        }
		}
    ]; 	

	const handleSearch = (optional, pageInfo)=>{		
		fetchCorrectionList({ ...optional, ...pageInfo });
	}
	const handleDelete = (code)=>{
		delTask({ missionCode:code })
		.then(res=>{
			if ( res.data.code === 200 ) {
				ElMessage({
					type:'success',
					message:'删除巡检任务成功！' 
				});
				fetchTaskList();
			}
		})
	}
	function handleOrder(rectifyId){
		setWorkOrder({ rectifyId })
		.then(res=>{
			if ( res.data.code === 200 ) {
				ElMessage({
					type:'success',
					message:'生成整改工单成功！' 
				});
				fetchCorrectionList();
			}
		})
	}
	const fetchCorrectionList = (params)=>{
		// 实际的axios请求;
		params = params || { };
		let realParams = { page:pageInfo.page, pageSize:pageInfo.pageSize };
		Object.keys(params).forEach(key=>{
			if ( params[key] ) {
				realParams[key] = params[key];
			}
		})
		const temp = realParams.startTime;
		if ( temp && temp.length && temp.length === 2 ) {
			let endTime = formatDateTime(temp[1], false) + ' 23:59:59';
			let startTime = formatDateTime(temp[0], false) + ' 00:00:00';
			realParams.startTime = startTime;
			realParams.endTime = endTime;
		}
		getCorrectionList(realParams)
		.then(res=>{
			if ( res.data.code === 200 ){
				tableData.value = res.data.data;
				total.value = res.data.total;
			}
		})
	};
	
	onMounted(()=>{
		let query = route.query;
		if ( query.id ) {
			fetchCorrectionList({ rectifyId:query.id });
		} else {
			fetchCorrectionList();
		}
		
	})
	
</script>
